<template>
  <div>
    <a-form-model ref="form" :model="model" :rules="validatorRules">
      <a-form-model-item required prop="username">
        <a-input class="input" v-model="model.username" size="large" placeholder="请输入帐户名或手机号">
          <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input>


      </a-form-model-item>
      <a-form-model-item required prop="password">
        <a-input v-model="model.password" size="large" type="password" autocomplete="false" placeholder="请输入密码">
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input>
      </a-form-model-item>

      <a-row :gutter="0">
        <a-col :span="15" v-if="mobileCaptchaShow">
          <a-form-model-item prop="inputCode">
            <a-input class="input" v-model="model.inputCode" size="large" type="text" placeholder="请输入短信验证码">
              <a-icon slot="prefix" type="smile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8" style="text-align: right">
          <!--          <img v-if="requestCodeSuccess && !mobileCaptchaShow" style="margin-top: 2px;" :src="randCodeImage"-->
          <!--               @click="handleChangeCheckCode"/>-->
          <!--          <img v-if="!requestCodeSuccess && !mobileCaptchaShow" style="margin-top: 2px;"-->
          <!--               src="../../assets/checkcode.png" @click="handleChangeCheckCode"/>-->
          <a-button v-if="mobileCaptchaShow" :disabled="updateDisableFlag" style="margin-top: 4px;margin-left: 3px"
                    @click="getPhoneCaptcha">{{ this.buttonShowText }}
          </a-button>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>

<script>
import {getAction} from '@/api/manage'
import {mapActions} from 'vuex'
import {checkDeviceFirstLogin, getPhoneCaptcha, phoneLogin, PhoneLoginWithSmsCode} from '@api/login'
import Fingerprint2 from 'fingerprintjs2'
import Vue from 'vue'
import {ACCESS_TOKEN, UI_CACHE_DB_DICT_DATA, USER_INFO, USER_NAME} from '@/store/mutation-types'
import {welcome} from '@/utils/util'
import store from '@/store'

export default {
  name: 'LoginAccount',
  data() {
    return {

      buttonShowText: '获取短信验证码',
      updateDisableFlag: false,
      settimer: 21,

      requestCodeSuccess: false,
      randCodeImage: '',
      currdatetime: '',
      loginType: 0,
      mobileCaptchaShow: false,
      mobileFromUserNameOrPhone: "",
      model: {
        username: '',
        password: '',
        inputCode: ''
      },
      validatorRules: {
        username: [
          //{ required: true, message: '请输入用户名!' },
          //{ validator: this.handleUsernameOrEmail }
        ],
        password: [{
          //required: true, message: '请输入密码!', validator: 'click'
        }],
        inputCode: [{
          //required: true, message: '请输入验证码!'
        }]
      }

    }
  },
  created: function () {
    this.handleChangeCheckCode()

    // 您不应在页面加载时或加载后直接运行指纹。 而是使用setTimeout或requestIdleCallback将其延迟几毫秒，以确保指纹一致。
    if (window.requestIdleCallback) {
      requestIdleCallback(() => {
        this.createFingerprint()
        //let deviceId = localStorage.getItem('browserId')
        //this.checkDeviceFirstLogin(deviceId);
      })
    } else {
      setTimeout(() => {
        this.createFingerprint()
        //let deviceId = localStorage.getItem('browserId')
        //this.checkDeviceFirstLogin(deviceId)
      }, 500)
    }

  },
  methods: {
    ...mapActions(['Login']),

    reportBtn() {
      let that = this
      let timer = setInterval(function () {
        that.updateDisableFlag = true
        that.settimer--
        if (that.settimer === 0) {
          clearInterval(timer)
          that.updateDisableFlag = false
          that.settimer = 21
        }
      }, 1000)
    },

    // 创建浏览器指纹
    createFingerprint() {
      // 选择哪些信息作为浏览器指纹生成的依据
      const options = {
        fonts: {
          extendedJsFonts: true,
        },
        excludes: {
          audio: true,
          userAgent: true,
          enumerateDevices: true,
          touchSupport: true,
        },
      }

      // 浏览器指纹
      Fingerprint2.get(options, (components) => { // 参数只有回调函数或者options为{}时，默认浏览器指纹依据所有配置信息进行生成
        const values = components.map(component => component.value) // 配置的值的数组
        const murmur = Fingerprint2.x64hash128(values.join(''), 31) // 生成浏览器指纹
        localStorage.setItem('browserId', murmur) // 存储浏览器指纹，在项目中用于校验用户身份和埋点
      })
    },

    checkDeviceFirstLogin(deviceId) {
      let param = {};
      param.deviceId = deviceId;
      checkDeviceFirstLogin(param).then(response => {
        if (response.code === 0) {
          let flag = response.result;
          if (flag === '1') {
            this.mobileCaptchaShow = true;
          }
        }
      })
    },

    /**刷新验证码*/
    handleChangeCheckCode() {
      this.currdatetime = new Date().getTime()
      this.model.inputCode = ''
      getAction(`/sys/randomImage/${this.currdatetime}`).then(res => {
        if (res.success) {
          this.randCodeImage = res.result
          this.requestCodeSuccess = true
        } else {
          this.$message.error(res.message)
          this.requestCodeSuccess = false
        }
      }).catch(() => {
        this.requestCodeSuccess = false
      })
    },

    getPhoneCaptcha() {
      let param = {}
      param.mobile = this.mobileFromUserNameOrPhone;
      param.smsmode = '0'
      getPhoneCaptcha(param).then(response => {
        if (response.success === false) {
          this.$message.error("手机号: " + this.mobileFromUserNameOrPhone + " 短信发送失败,"+response.message)
        } else if (response.success === true) {
          this.$message.info("手机号: " + this.mobileFromUserNameOrPhone + " 短信发送成功")
          this.reportBtn();
        }
      })

    },

    // 判断登录类型
    handleUsernameOrEmail(rule, value, callback) {
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        this.loginType = 0
      } else {
        this.loginType = 1
      }
      callback()
    },
    /**
     * 验证字段
     * @param arr
     * @param callback
     */
    validateFields(arr, callback) {
      let promiseArray = []
      for (let item of arr) {
        let p = new Promise((resolve, reject) => {
          this.$refs['form'].validateField(item, (err) => {
            if (!err) {
              resolve()
            } else {
              reject(err)
            }
          })
        })
        promiseArray.push(p)
      }
      Promise.all(promiseArray).then(() => {
        callback()
      }).catch(err => {
        callback(err)
      })
    },
    acceptUsername(username) {
      this.model['username'] = username
    },

    //手机号登录
    PhoneLogin3(userInfo) {
      return new Promise((resolve, reject) => {
        phoneLogin(userInfo).then(response => {
          if (response.code === 200) {
            const result = response.result
            const userInfo = result.userInfo
            Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
            store.commit('SET_TOKEN', result.token)
            store.commit('SET_INFO', userInfo)
            store.commit('SET_NAME', {username: userInfo.username, realname: userInfo.realname, welcome: welcome()})
            store.commit('SET_AVATAR', userInfo.avatar)
            resolve(response)
          } else {
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    //手机号登录
    PhoneLoginWithSmsCode(userInfo) {
      return new Promise((resolve, reject) => {
        PhoneLoginWithSmsCode(userInfo).then(response => {
          if (response.code === 200) {
            const result = response.result
            const userInfo = result.userInfo
            Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
            store.commit('SET_TOKEN', result.token)
            store.commit('SET_INFO', userInfo)
            store.commit('SET_NAME', {username: userInfo.username, realname: userInfo.realname, welcome: welcome()})
            store.commit('SET_AVATAR', userInfo.avatar)
            resolve(response)
          } else {
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    //账号密码登录
    handleLogin(rememberMe) {
      let loginParams = {
        username: this.model.username,
        deviceId: localStorage.getItem('browserId'),
        password: this.model.password,
        captcha: this.model.inputCode,
        checkKey: this.currdatetime,
        remember_me: rememberMe,
        mobile: this.model.username,
        operateType: 4, // 4电脑登录
      }

      console.log('登录参数', loginParams)
      this.PhoneLoginWithSmsCode(loginParams).then((res) => {
        if (res.result != null && res.result.status != null && res.result.status === "success") {
          this.$emit('success', res.result)
        } else if (res.result.status != null && (res.result.status === "no captcha" || res.result.status === "error captcha")) {
          this.mobileCaptchaShow = true;
          this.mobileFromUserNameOrPhone = res.result.phone;
          this.$emit('fail', res.success)
        }
      }).catch((err) => {
        if (err.result != null && err.result.status != null && (err.result.status === "no captcha" || err.result.status === "error captcha")) {
          this.mobileCaptchaShow = true;
          this.mobileFromUserNameOrPhone = err.result.phone;
        }
        this.$emit('fail', err)
      })

    }

  }

}
</script>

<style scoped>
.input /deep/ .ant-input {
  height: 40px;
}
</style>